package controllers

import (
	"database/sql"
	"fmt"
	"github.com/beego/beego/v2/core/logs"
	beego "github.com/beego/beego/v2/server/web"
	_ "github.com/go-sql-driver/mysql"
	"mt_go_app/db/oracle/orm"
	"mt_go_app/models"
)

type MainController struct {
	beego.Controller
}

func (c *MainController) Get() {
	logs.SetLogger("console")
	logs.Info("this %s cat is %v years old", "yellow", 3)
	c.Ctx.WriteString("hello")

	// 默认使用 default，你可以指定为其他数据库
	o := orm.NewOrm()

	user := models.User{Id: 1}
	err := o.Read(&user)
	if err == orm.ErrNoRows {
		fmt.Println("查询不到,开始插入...")
		user := new(models.User)
		profile := new(models.Profile)
		profile.Age = 30
		user.Profile = profile
		user.Name = "slene"
		fmt.Println(o.Insert(profile))
		fmt.Println(o.Insert(user))
	} else if err == orm.ErrMissPK {
		fmt.Println("找不到主键")
	} else {
		fmt.Println(user.Id, user.Name)
		user.Name = "Your"
		fmt.Println(o.Update(&user))
		fmt.Println(o.Read(&user))
	}
}

func (c *MainController) GetOraConn() {
	// 设置连接数据库的参数
	db, _ := sql.Open("oci8", "BSS_MAIMAI_BEIJING:BSS_MAIMAI_BEIJING@172.16.12.137:1521/BSSBAKPDB12_20210427")
	//获取所有数据
	rows, _ := db.Query("select id as CODE,USER_NAME AS NAME from sys_user where user_login_name='admin'")
	var CODE, NAME string
	//循环显示所有的数据
	for rows.Next() {
		rows.Scan(&CODE, &NAME)
		fmt.Println(CODE, "--", NAME)
	}

	//关闭数据库
	defer db.Close()
	//连接数据库
	err := db.Ping()
	if err != nil {
		c.Ctx.WriteString("数据库连接失败")
		return
	}
	c.Ctx.WriteString("hello oracle!")
}

func (c *MainController) Post() {
	logs.SetLogger("console")
	logs.Info("this %s cat is %v years old", "yellow", 3)
	c.Ctx.WriteString("hello")

	// 默认使用 default，你可以指定为其他数据库
	o := orm.NewOrm()
	var users []*models.Usertemp
	num, err := o.QueryTable("usertemp").Limit(2).Offset(2).All(&users)
	fmt.Printf("Affected Num: %v, %v\n", num, err)
	fmt.Println(users)
	for _, u := range users {
		fmt.Printf(u.Name)
	}

	/*user:= models.Usertemp{Id:1}
	o.Read(&user)
	user.Name = "hh"
	o.Update(&user)*/

}
